package com.gac.keepalive

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import java.util.*


/**
 * FileName: OptimizeBattery
 * Author: gacmy
 * Date: 2021/10/9 9:49 AM
 * Description:
 */
class OptimizeBattery :Fragment() {

    private val mCallbacks = SparseArray<IPermissionListener>()

    private val mCodeGenerator: Random = Random()



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true

    }

    /**
     * 随机生成唯一的requestCode，最多尝试10次
     *
     * @return
     */
    private fun makeRequestCode(): Int {
        var requestCode: Int
        var tryCount = 0
        do {
            requestCode = mCodeGenerator.nextInt(0x0000FFFF)
            tryCount++
        } while (mCallbacks.indexOfKey(requestCode) >= 0 && tryCount < 10)
        return requestCode
    }



    fun requestBattery(listener: IPermissionListener){
        val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
        val requestCode = makeRequestCode()
        Log.e("gacmy","requestBattery")
        mCallbacks.put(requestCode, listener)
        intent.data = Uri.parse("package:${context?.packageName}")
        //启动忽略电池优化，会弹出一个系统的弹框，我们在上面的
        startActivityForResult(intent, makeRequestCode())
    }


    fun queryBatteryOptimizeStatus():Boolean{
        val powerManager = context?.getSystemService(Context.POWER_SERVICE) as PowerManager?
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            powerManager?.isIgnoringBatteryOptimizations(context?.packageName)?:false
        } else {
            true
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("gacmy","requestCode:::${requestCode} resultCode:${resultCode} ${queryBatteryOptimizeStatus()}")
        val callback = mCallbacks[requestCode]
        mCallbacks.remove(requestCode)
        if (callback == null) {
            return
        }
        callback.onAccepted(queryBatteryOptimizeStatus())

    }



}